package com.horoscope.astrology.zodiac.signs.free.adapter

import android.content.Context
import android.os.Bundle
import android.util.SparseArray
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.fragment.article.ArticleSubFragment
import com.horoscope.astrology.zodiac.signs.free.fragment.article.QuizzesSubFragment

/**
 * Article和Quizzes 顶部TableLayout绑定ViewPager 的 适配器
 * 主要做滑动切换 点击切换 title的改变
 * 对应 ArticleFragment和QuizzesActivity
 * */
class ArticlePageFragmentAdapter(
    private val mContext: Context,
    private val flag: Int,
    fm: FragmentManager
) :
    FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {


    private val sparseArray = SparseArray<Fragment>()

    override fun getCount(): Int {
        return if (flag == 1) {
            mTitleQuizzes.size
        } else {
            mTitleArticle.size
        }
    }

    override fun getItem(position: Int): Fragment {
        return if (sparseArray[position] == null) {
            val bundle = Bundle()
            bundle.putInt("position", position)
            if (flag == 1) {
                val quizzesFragment = QuizzesSubFragment()
                bundle.putString("title", QuizzesSubFragment.title(position))
                quizzesFragment.arguments = bundle
                sparseArray.put(position, quizzesFragment)
                quizzesFragment
            } else {
                val articleFragment = ArticleSubFragment()
                bundle.putString("title", ArticleSubFragment.title(position))
                articleFragment.arguments = bundle
                sparseArray.put(position, articleFragment)
                articleFragment
            }
        } else {
            sparseArray[position]
        }
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return if (flag == 1) {
            mContext.getString(mTitleQuizzes[position])
        } else {
            mContext.getString(mTitleArticle[position])
        }
    }


    private var mCurrentPosition = 0
    fun setCurrentPosition(position: Int) {
        mCurrentPosition = position
    }

    fun notifyAd() {
        if (flag == 1) {
            (sparseArray[mCurrentPosition] as QuizzesSubFragment).notifyAdapter()
        } else {
            (sparseArray[mCurrentPosition] as ArticleSubFragment).notifyAd()
        }
    }

    companion object {
        val mTitleArticle = intArrayOf(
            R.string.fragment_hot_title,
            R.string.fragment_love_title,
            R.string.text_career,
            R.string.fragment_other_title
        )
        val mTitleQuizzes = intArrayOf(
            R.string.text_Newest,
            R.string.text_Hottest
        )
    }

}